home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part2 / 16688 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.4 KB  |  75 lines

  1. Path: news.th-darmstadt.de!news
  2. From: Enno Sandner <enno@intellektik.informatik.th-darmstadt.de>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Creating an object via new with ONLY a pointer to the object
  5. Date: Thu, 11 Apr 1996 15:08:44 +0200
  6. Organization: Fachbereich Informatik, TH Darmstadt
  7. Message-ID: <316D045C.59E2B600@intellektik.informatik.th-darmstadt.de>
  8. References: <4kh07v$lno@crchh327.rich.bnr.ca>
  9. NNTP-Posting-Host: kitz.intellektik.informatik.th-darmstadt.de
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.01 (X11; I; SunOS 4.1.3 sun4m)
  14.  
  15. Bret Bieghler wrote:
  16. > An interesting problem I've come across... I was wondering if this
  17. > is possible:
  18. > I have a generic CommandObject which defines several pure virtual
  19. > functions.  Derived from CommandObject are user commands, such
  20. > as ExitCommand, StatusCommand, etc.
  21. > To process a command (currently) I do the following:
  22. >         CommandObject* basePtr;
  23. >         if (command == "exit")
  24. >         {
  25. >                 basePtr = new ExitCommand;
  26. >                 basePtr->implement();
  27. >         }
  28. >         else if (command == "status")
  29. >         {
  30. >                 basePtr = new StatusCommand;
  31. >                 basePtr->implement();
  32. >         }
  33. > What I would LIKE to do is the the following:
  34. >         CommandObject* basePtr =  new commandTable[command];
  35. > where commandTable is an associative array as follows:
  36. >         Key             Value
  37. >         "exit"  ExitCommand*
  38. >         "status"        StatusCommand*
  39. > The problem is if there is a way to create a new object
  40. > of a given type having only a pointer to that type.
  41. > Is this possible?
  42.  
  43. There's no direct languages support for such a thing in C++, but
  44. you can maintain a set of (<command-name>,<creation-func>) tuples
  45. in a map. The <creation-func> is a func of type 'CommandObject* (*)()'
  46. which returns a newly created object of the appropriate subclass
  47. of 'CommandObject'. You may choose these functions as static
  48. member-functions of the subclasses of 'CommandObject', e.g.
  49.  
  50.         class MyOwnCommand : public CommandObject {
  51.           ...
  52.           public:
  53.           static CommandObject* Create() {
  54.                  return new MyOwnCommand;
  55.           }
  56.           ...
  57.          };
  58.  
  59. There're several other solutions but this one is IMO the minimal
  60. extension of the idea you already had.
  61.  
  62.     Enno
  63.